import { createSlice } from "@reduxjs/toolkit";
import { removeToken } from "@/utils/index";
import { setToken as addToken, getToken } from "@/utils/index";
import { apiGetToken, apigetUserInfo } from "@/apis/user";
const Userstore = createSlice({
  name: "user",
  initialState: {
    token: getToken("token") || "",
    userInfo: {},
    redirectUrl: "/",
  },
  reducers: {
    setToken(state, { payload }) {
      state.token = payload;
      addToken("token", payload);
    },
    setUerInfo(state, { payload }) {
      state.userInfo = payload;
    },
    clearUser(state) {
      state.token = "";
      state.userInfo = {};
      removeToken();
    },
    setRedirectUrl(state, { payload }) {
      state.redirectUrl = payload;
    },
  },
});

const { setToken, setUerInfo, clearUser, setRedirectUrl } = Userstore.actions;

const userRecuer = Userstore.reducer;

const fetchLogin = (loginForm) => {
  return async (dispatch) => {
    const res = await apiGetToken(loginForm);
    dispatch(setToken(res.data.token));
  };
};

//获取信息
const fetchUserInfo = () => {
  return async (dispatch) => {
    const res = await apigetUserInfo();
    dispatch(setUerInfo(res.data));
  };
};
export { fetchLogin, fetchUserInfo, clearUser, setRedirectUrl };
export default userRecuer;
